home *** CD-ROM | disk | FTP | other *** search
/ Light ROM 1 / LIGHT-ROM 1 (Amiga Library Services)(1994).iso / ffdisks / d982.lha / HWGRCS / HWGpatchP1_2_1.lha / patch-2.1 / src / patch.c < prev    next >
C/C++ Source or Header  |  1993-11-30  |  28KB  |  946 lines

  1. char rcsid[] =
  2.         "$Header: patch.c,v 2.0.2.0 90/05/01 22:17:50 davison Locked $";
  3.  
  4. /* patch - a program to apply diffs to original files
  5.  *
  6.  * Copyright 1986, Larry Wall
  7.  *
  8.  * This program may be copied as long as you don't try to make any
  9.  * money off of it, or pretend that you wrote it.
  10.  *
  11.  * $Log:        patch.c,v $
  12.  * Revision 2.0.2.0  90/05/01  22:17:50  davison
  13.  * patch12u: unidiff support added
  14.  *
  15.  * Revision 2.0.1.6  88/06/22  20:46:39  lwall
  16.  * patch12: rindex() wasn't declared
  17.  *
  18.  * Revision 2.0.1.5  88/06/03  15:09:37  lwall
  19.  * patch10: exit code improved.
  20.  * patch10: better support for non-flexfilenames.
  21.  *
  22.  * Revision 2.0.1.4  87/02/16  14:00:04  lwall
  23.  * Short replacement caused spurious "Out of sync" message.
  24.  *
  25.  * Revision 2.0.1.3  87/01/30  22:45:50  lwall
  26.  * Improved diagnostic on sync error.
  27.  * Moved do_ed_script() to pch.c.
  28.  *
  29.  * Revision 2.0.1.2  86/11/21  09:39:15  lwall
  30.  * Fuzz factor caused offset of installed lines.
  31.  *
  32.  * Revision 2.0.1.1  86/10/29  13:10:22  lwall
  33.  * Backwards search could terminate prematurely.
  34.  *
  35.  * Revision 2.0  86/09/17  15:37:32  lwall
  36.  * Baseline for netwide release.
  37.  *
  38.  * Revision 1.5  86/08/01  20:53:24  lwall
  39.  * Changed some %d's to %ld's.
  40.  * Linted.
  41.  *
  42.  * Revision 1.4  86/08/01  19:17:29  lwall
  43.  * Fixes for machines that can't vararg.
  44.  * Added fuzz factor.
  45.  * Generalized -p.
  46.  * General cleanup.
  47.  *
  48.  * 85/08/15 van%ucbmonet@berkeley
  49.  * Changes for 4.3bsd diff -c.
  50.  *
  51.  * Revision 1.3  85/03/26  15:07:43  lwall
  52.  * Frozen.
  53.  *
  54.  * Revision 1.2.1.9  85/03/12  17:03:35  lwall
  55.  * Changed pfp->_file to fileno(pfp).
  56.  *
  57.  * Revision 1.2.1.8  85/03/12  16:30:43  lwall
  58.  * Check i_ptr and i_womp to make sure they aren't null before freeing.
  59.  * Also allow ed output to be suppressed.
  60.  *
  61.  * Revision 1.2.1.7  85/03/12  15:56:13  lwall
  62.  * Added -p option from jromine@uci-750a.
  63.  *
  64.  * Revision 1.2.1.6  85/03/12  12:12:51  lwall
  65.  * Now checks for normalness of file to patch.
  66.  *
  67.  * Revision 1.2.1.5  85/03/12  11:52:12  lwall
  68.  * Added -D (#ifdef) option from joe@fluke.
  69.  *
  70.  * Revision 1.2.1.4  84/12/06  11:14:15  lwall
  71.  * Made smarter about SCCS subdirectories.
  72.  *
  73.  * Revision 1.2.1.3  84/12/05  11:18:43  lwall
  74.  * Added -l switch to do loose string comparison.
  75.  *
  76.  * Revision 1.2.1.2  84/12/04  09:47:13  lwall
  77.  * Failed hunk count not reset on multiple patch file.
  78.  *
  79.  * Revision 1.2.1.1  84/12/04  09:42:37  lwall
  80.  * Branch for sdcrdcf changes.
  81.  *
  82.  * Revision 1.2  84/11/29  13:29:51  lwall
  83.  * Linted.  Identifiers uniqified.  Fixed i_ptr malloc() bug.  Fixed
  84.  * multiple calls to mktemp().  Will now work on machines that can only
  85.  * read 32767 chars.  Added -R option for diffs with new and old swapped.
  86.  * Various cosmetic changes.
  87.  *
  88.  * Revision 1.1  84/11/09  17:03:58  lwall
  89.  * Initial revision
  90.  *
  91.  */
  92.  
  93. #include "INTERN.h"
  94. #include "common.h"
  95. #include "EXTERN.h"
  96. #include "version.h"
  97. #include "util.h"
  98. #include "pch.h"
  99. #include "inp.h"
  100. #include "backupfile.h"
  101. #include "getopt.h"
  102.  
  103. /* procedures */
  104.  
  105. void reinitialize_almost_everything();
  106. void get_some_switches();
  107. LINENUM locate_hunk();
  108. void abort_hunk();
  109. void apply_hunk();
  110. void init_output();
  111. void init_reject();
  112. void copy_till();
  113. void spew_output();
  114. void dump_line();
  115. bool patch_match();
  116. bool similar();
  117. void re_input();
  118. void my_exit();
  119.  
  120. /* TRUE if -E was specified on command line.  */
  121. static int remove_empty_files = FALSE;
  122.  
  123. /* TRUE if -R was specified on command line.  */
  124. static int reverse_flag_specified = FALSE;
  125.  
  126. /* Apply a set of diffs as appropriate. */
  127.  
  128. int
  129. main(argc,argv)
  130. int argc;
  131. char **argv;
  132. {
  133.     LINENUM where;
  134.     LINENUM newwhere;
  135.     LINENUM fuzz;
  136.     LINENUM mymaxfuzz;
  137.     int hunk = 0;
  138.     int failed = 0;
  139.     int failtotal = 0;
  140.     bool rev_okayed = 0;
  141.     int i;
  142.  
  143.     setbuf(stderr, serrbuf);
  144.     for (i = 0; i<MAXFILEC; i++)
  145.         filearg[i] = Nullch;
  146.  
  147.     myuid = getuid();
  148.  
  149.     /* Cons up the names of the temporary files.  */
  150.     {
  151.       /* Directory for temporary files.  */
  152.       char *tmpdir;
  153.       int tmpname_len;
  154.  
  155.       tmpdir = getenv ("TMPDIR");
  156.       if (tmpdir == NULL) {
  157.         tmpdir = TMPDIRECTORY;
  158.       }
  159.       tmpname_len = strlen (tmpdir) + 20;
  160.  
  161.       TMPOUTNAME = (char *) malloc (tmpname_len);
  162.       strcpy (TMPOUTNAME, tmpdir);
  163.       strcat (TMPOUTNAME, "patchoXXXXXX");
  164.       Mktemp(TMPOUTNAME);
  165.  
  166.       TMPINNAME = (char *) malloc (tmpname_len);
  167.       strcpy (TMPINNAME, tmpdir);
  168.       strcat (TMPINNAME, "patchiXXXXXX");
  169.       Mktemp(TMPINNAME);
  170.  
  171.       TMPREJNAME = (char *) malloc (tmpname_len);
  172.       strcpy (TMPREJNAME, tmpdir);
  173.       strcat (TMPREJNAME, "patchrXXXXXX");
  174.       Mktemp(TMPREJNAME);
  175.  
  176.       TMPPATNAME = (char *) malloc (tmpname_len);
  177.       strcpy (TMPPATNAME, tmpdir);
  178.       strcat (TMPPATNAME, "patchpXXXXXX");
  179.       Mktemp(TMPPATNAME);
  180.     }
  181.  
  182.     {
  183.       char *v;
  184.  
  185.       v = getenv ("SIMPLE_BACKUP_SUFFIX");
  186.       if (v)
  187.         simple_backup_suffix = v;
  188.       else
  189.         simple_backup_suffix = ".orig";
  190. #ifndef NODIR
  191.       v = getenv ("VERSION_CONTROL");
  192.       backup_type = get_version (v); /* OK to pass NULL. */
  193. #endif
  194.     }
  195.  
  196.     /* parse switches */
  197.     Argc = argc;
  198.     Argv = argv;
  199.     get_some_switches();
  200.  
  201.     /* make sure we clean up /tmp in case of disaster */
  202.     set_signals(0);
  203.  
  204.     for (
  205.         open_patch_file(filearg[1]);
  206.         there_is_another_patch();
  207.         reinitialize_almost_everything()
  208.     ) {                                 /* for each patch in patch file */
  209.  
  210.         if (outname == Nullch)
  211.             outname = savestr(filearg[0]);
  212.  
  213.         /* for ed script just up and do it and exit */
  214.         if (diff_type == ED_DIFF) {
  215.             do_ed_script();
  216.             continue;
  217.         }
  218.  
  219.         /* initialize the patched file */
  220.         if (!skip_rest_of_patch)
  221.             init_output(TMPOUTNAME);
  222.  
  223.         /* initialize reject file */
  224.         init_reject(TMPREJNAME);
  225.  
  226.         /* find out where all the lines are */
  227.         if (!skip_rest_of_patch)
  228.             scan_input(filearg[0]);
  229.  
  230.         /* from here on, open no standard i/o files, because malloc */
  231.         /* might misfire and we can't catch it easily */
  232.  
  233.         /* apply each hunk of patch */
  234.         hunk = 0;
  235.         failed = 0;
  236.         rev_okayed = FALSE;
  237.         out_of_mem = FALSE;
  238.         while (another_hunk()) {
  239.             hunk++;
  240.             fuzz = Nulline;
  241.             mymaxfuzz = pch_context();
  242.             if (maxfuzz < mymaxfuzz)
  243.                 mymaxfuzz = maxfuzz;
  244.             if (!skip_rest_of_patch) {
  245.                 do {
  246.                     where = locate_hunk(fuzz);
  247.                     if (hunk == 1 && where == Nulline && !(force|rev_okayed)) {
  248.                                                 /* dwim for reversed patch? */
  249.                         if (!pch_swap()) {
  250.                             if (fuzz == Nulline)
  251.                                 say1(
  252. "Not enough memory to try swapped hunk!  Assuming unswapped.\n");
  253.                             continue;
  254.                         }
  255.                         reverse = !reverse;
  256.                         where = locate_hunk(fuzz);  /* try again */
  257.                         if (where == Nulline) {     /* didn't find it swapped */
  258.                             if (!pch_swap())         /* put it back to normal */
  259.                                 fatal1("lost hunk on alloc error!\n");
  260.                             reverse = !reverse;
  261.                         }
  262.                         else if (noreverse) {
  263.                             if (!pch_swap())         /* put it back to normal */
  264.                                 fatal1("lost hunk on alloc error!\n");
  265.                             reverse = !reverse;
  266.                             say1(
  267. "Ignoring previously applied (or reversed) patch.\n");
  268.                             skip_rest_of_patch = TRUE;
  269.                         }
  270.                         else if (batch) {
  271.                             if (verbose)
  272.                                 say3(
  273. "%seversed (or previously applied) patch detected!  %s -R.",
  274.                                 reverse ? "R" : "Unr",
  275.                                 reverse ? "Assuming" : "Ignoring");
  276.                         }
  277.                         else {
  278.                             ask3(
  279. "%seversed (or previously applied) patch detected!  %s -R? [y] ",
  280.                                 reverse ? "R" : "Unr",
  281.                                 reverse ? "Assume" : "Ignore");
  282.                             if (*buf == 'n') {
  283.                                 ask1("Apply anyway? [n] ");
  284.                                 if (*buf == 'y')
  285.                                     rev_okayed = TRUE;
  286.                                 else
  287.                                     skip_rest_of_patch = TRUE;
  288.                                 where = Nulline;
  289.                                 reverse = !reverse;
  290.                                 if (!pch_swap())  /* put it back to normal */
  291.                                     fatal1("lost hunk on alloc error!\n");
  292.                             }
  293.                         }
  294.                     }
  295.                 } while (!skip_rest_of_patch && where == Nulline &&
  296.                     ++fuzz <= mymaxfuzz);
  297.  
  298.                 if (skip_rest_of_patch) {               /* just got decided */
  299.                     Fclose(ofp);
  300.                     ofp = Nullfp;
  301.                 }
  302.             }
  303.  
  304.             newwhere = pch_newfirst() + last_offset;
  305.             if (skip_rest_of_patch) {
  306.                 abort_hunk();
  307.                 failed++;
  308.                 if (verbose)
  309.                     say3("Hunk #%d ignored at %ld.\n", hunk, newwhere);
  310.             }
  311.             else if (where == Nulline) {
  312.                 abort_hunk();
  313.                 failed++;
  314.                 if (verbose)
  315.                     say3("Hunk #%d failed at %ld.\n", hunk, newwhere);
  316.             }
  317.             else {
  318.                 apply_hunk(where);
  319.                 if (verbose) {
  320.                     say3("Hunk #%d succeeded at %ld", hunk, newwhere);
  321.                     if (fuzz)
  322.                         say2(" with fuzz %ld", fuzz);
  323.                     if (last_offset)
  324.                         say3(" (offset %ld line%s)",
  325.                             last_offset, last_offset==1L?"":"s");
  326.                     say1(".\n");
  327.                 }
  328.             }
  329.         }
  330.  
  331.         if (out_of_mem && using_plan_a) {
  332.             optind = optind_last;
  333.             say1("\n\nRan out of memory using Plan A--trying again...\n\n");
  334.             if (ofp)
  335.                 Fclose(ofp);
  336.             ofp = Nullfp;
  337.             if (rejfp)
  338.                 Fclose(rejfp);
  339.             rejfp = Nullfp;
  340.             continue;
  341.         }
  342.  
  343.         assert(hunk);
  344.  
  345.         /* finish spewing out the new file */
  346.         if (!skip_rest_of_patch)
  347.             spew_output();
  348.  
  349.         /* and put the output where desired */
  350.         ignore_signals();
  351.         if (!skip_rest_of_patch) {
  352.             struct stat statbuf;
  353.             char *realout = outname;
  354.  
  355.             if (move_file(TMPOUTNAME, outname) < 0) {
  356.                 toutkeep = TRUE;
  357.                 realout = TMPOUTNAME;
  358.                 chmod(TMPOUTNAME, filemode);
  359.             }
  360.             else
  361.                 chmod(outname, filemode);
  362.  
  363.             if (remove_empty_files && stat(realout, &statbuf) == 0
  364.                 && statbuf.st_size == 0) {
  365.                 if (verbose)
  366.                     say2("Removing %s (empty after patching).\n", realout);
  367.                 while (unlink(realout) >= 0) ; /* while is for Eunice.  */
  368.             }
  369.         }
  370.         Fclose(rejfp);
  371.         rejfp = Nullfp;
  372.         if (failed) {
  373.             failtotal += failed;
  374.             if (!*rejname) {
  375.                 Strcpy(rejname, outname);
  376.                 addext(rejname, ".rej", '#');
  377.             }
  378.             if (skip_rest_of_patch) {
  379.                 say4("%d out of %d hunks ignored--saving rejects to %s\n",
  380.                     failed, hunk, rejname);
  381.             }
  382.             else {
  383.                 say4("%d out of %d hunks failed--saving rejects to %s\n",
  384.                     failed, hunk, rejname);
  385.             }
  386.             if (move_file(TMPREJNAME, rejname) < 0)
  387.                 trejkeep = TRUE;
  388.         }
  389.         set_signals(1);
  390.     }
  391.     my_exit(failtotal);
  392. }
  393.  
  394. /* Prepare to find the next patch to do in the patch file. */
  395.  
  396. void
  397. reinitialize_almost_everything()
  398. {
  399.     re_patch();
  400.     re_input();
  401.  
  402.     input_lines = 0;
  403.     last_frozen_line = 0;
  404.  
  405.     filec = 0;
  406.     if (filearg[0] != Nullch && !out_of_mem) {
  407.         free(filearg[0]);
  408.         filearg[0] = Nullch;
  409.     }
  410.  
  411.     if (outname != Nullch) {
  412.         free(outname);
  413.         outname = Nullch;
  414.     }
  415.  
  416.     last_offset = 0;
  417.  
  418.     diff_type = 0;
  419.  
  420.     if (revision != Nullch) {
  421.         free(revision);
  422.         revision = Nullch;
  423.     }
  424.  
  425.     reverse = reverse_flag_specified;
  426.     skip_rest_of_patch = FALSE;
  427.  
  428.     get_some_switches();
  429.  
  430.     if (filec >= 2)
  431.         fatal1("you may not change to a different patch file\n");
  432. }
  433.  
  434. static char *shortopts = "-b:B:cd:D:eEfF:lnNo:p::r:RsStuvV:x:";
  435. static struct option longopts[] =
  436. {
  437.   {"suffix", 1, NULL, 'b'},
  438.   {"prefix", 1, NULL, 'B'},
  439.   {"context", 0, NULL, 'c'},
  440.   {"directory", 1, NULL, 'd'},
  441.   {"ifdef", 1, NULL, 'D'},
  442.   {"ed", 0, NULL, 'e'},
  443.   {"remove-empty-files", 0, NULL, 'E'},
  444.   {"force", 0, NULL, 'f'},
  445.   {"fuzz", 1, NULL, 'F'},
  446.   {"ignore-whitespace", 0, NULL, 'l'},
  447.   {"normal", 0, NULL, 'n'},
  448.   {"forward", 0, NULL, 'N'},
  449.   {"output", 1, NULL, 'o'},
  450.   {"strip", 2, NULL, 'p'},
  451.   {"reject-file", 1, NULL, 'r'},
  452.   {"reverse", 0, NULL, 'R'},
  453.   {"quiet", 0, NULL, 's'},
  454.   {"silent", 0, NULL, 's'},
  455.   {"skip", 0, NULL, 'S'},
  456.   {"batch", 0, NULL, 't'},
  457.   {"unified", 0, NULL, 'u'},
  458.   {"version", 0, NULL, 'v'},
  459.   {"version-control", 1, NULL, 'V'},
  460.   {"debug", 1, NULL, 'x'},
  461.   {0, 0, 0, 0}
  462. };
  463.  
  464. /* Process switches and filenames up to next '+' or end of list. */
  465.  
  466. void
  467. get_some_switches()
  468. {
  469.     Reg1 int optc;
  470.  
  471.     rejname[0] = '\0';
  472.     optind_last = optind;
  473.     if (optind == Argc)
  474.         return;
  475.     while ((optc = getopt_long (Argc, Argv, shortopts, longopts, (int *) 0))
  476.            != -1) {
  477.         if (optc == 1) {
  478.             if (strEQ(optarg, "+"))
  479.                 return;
  480.             if (filec == MAXFILEC)
  481.                 fatal1("too many file arguments\n");
  482.             filearg[filec++] = savestr(optarg);
  483.         }
  484.         else {
  485.             switch (optc) {
  486.             case 'b':
  487.                 simple_backup_suffix = savestr(optarg);
  488.                 break;
  489.             case 'B':
  490.                 origprae = savestr(optarg);
  491.                 break;
  492.             case 'c':
  493.                 diff_type = CONTEXT_DIFF;
  494.                 break;
  495.             case 'd':
  496.                 if (chdir(optarg) < 0)
  497.                     pfatal2("can't cd to %s", optarg);
  498.                 break;
  499.             case 'D':
  500.                 do_defines = TRUE;
  501.                 if (!isalpha(*optarg) && '_' != *optarg)
  502.                     fatal1("argument to -D is not an identifier\n");
  503.                 Sprintf(if_defined, "#ifdef %s\n", optarg);
  504.                 Sprintf(not_defined, "#ifndef %s\n", optarg);
  505.                 Sprintf(end_defined, "#endif /* %s */\n", optarg);
  506.                 break;
  507.             case 'e':
  508.                 diff_type = ED_DIFF;
  509.                 break;
  510.             case 'E':
  511.                 remove_empty_files = TRUE;
  512.                 break;
  513.             case 'f':
  514.                 force = TRUE;
  515.                 break;
  516.             case 'F':
  517.                 maxfuzz = atoi(optarg);
  518.                 break;
  519.             case 'l':
  520.                 canonicalize = TRUE;
  521.                 break;
  522.             case 'n':
  523.                 diff_type = NORMAL_DIFF;
  524.                 break;
  525.             case 'N':
  526.                 noreverse = TRUE;
  527.                 break;
  528.             case 'o':
  529.                 outname = savestr(optarg);
  530.                 break;
  531.             case 'p':
  532.                 if (optarg)
  533.                     strippath = atoi(optarg);
  534.                 else
  535.                     strippath = 0;
  536.                 break;
  537.             case 'r':
  538.                 Strcpy(rejname, optarg);
  539.                 break;
  540.             case 'R':
  541.                 reverse = TRUE;
  542.                 reverse_flag_specified = TRUE;
  543.                 break;
  544.             case 's':
  545.                 verbose = FALSE;
  546.                 break;
  547.             case 'S':
  548.                 skip_rest_of_patch = TRUE;
  549.                 break;
  550.             case 't':
  551.                 batch = TRUE;
  552.                 break;
  553.             case 'u':
  554.                 diff_type = UNI_DIFF;
  555.                 break;
  556.             case 'v':
  557.                 version();
  558.                 break;
  559.             case 'V':
  560. #ifndef NODIR
  561.                 backup_type = get_version (optarg);
  562. #endif
  563.                 break;
  564. #ifdef DEBUGGING
  565.             case 'x':
  566.                 debug = atoi(optarg);
  567.                 break;
  568. #endif
  569.             default:
  570.                 fprintf(stderr, "\
  571. Usage: %s [options] [origfile [patchfile]] [+ [options] [origfile]]...\n",
  572.                         Argv[0]);
  573.                 fprintf(stderr, "\
  574. Options:\n\
  575.        [-ceEflnNRsStuv] [-b backup-ext] [-B backup-prefix] [-d directory]\n\
  576.        [-D symbol] [-F max-fuzz] [-o out-file] [-p[strip-count]]\n\
  577.        [-r rej-name] [-V {numbered,existing,simple}] [--context]\n\
  578.        [--prefix=backup-prefix] [--suffix=backup-ext] [--ifdef=symbol]\n\
  579.        [--directory=directory] [--ed] [--fuzz=max-fuzz] [--force] [--batch]\n\
  580.        [--ignore-whitespace] [--forward] [--reverse] [--output=out-file]\n");
  581.                 fprintf(stderr, "\
  582.        [--strip[=strip-count]] [--normal] [--reject-file=rej-name] [--skip]\n\
  583.        [--remove-empty-files] [--quiet] [--silent] [--unified] [--version]\n\
  584.        [--version-control={numbered,existing,simple}]\n");
  585.                 my_exit(1);
  586.             }
  587.         }
  588.     }
  589.  
  590.     /* Process any filename args given after "--".  */
  591.     for (; optind < Argc; ++optind) {
  592.         if (filec == MAXFILEC)
  593.             fatal1("too many file arguments\n");
  594.         filearg[filec++] = savestr(Argv[optind]);
  595.     }
  596. }
  597.  
  598. /* Attempt to find the right place to apply this hunk of patch. */
  599.  
  600. LINENUM
  601. locate_hunk(fuzz)
  602. LINENUM fuzz;
  603. {
  604.     Reg1 LINENUM first_guess = pch_first() + last_offset;
  605.     Reg2 LINENUM offset;
  606.     LINENUM pat_lines = pch_ptrn_lines();
  607.     Reg3 LINENUM max_pos_offset = input_lines - first_guess
  608.                                 - pat_lines + 1;
  609.     Reg4 LINENUM max_neg_offset = first_guess - last_frozen_line - 1
  610.                                 + pch_context();
  611.  
  612.     if (!pat_lines)                     /* null range matches always */
  613.         return first_guess;
  614.     if (max_neg_offset >= first_guess)  /* do not try lines < 0 */
  615.         max_neg_offset = first_guess - 1;
  616.     if (first_guess <= input_lines && patch_match(first_guess, Nulline, fuzz))
  617.         return first_guess;
  618.     for (offset = 1; ; offset++) {
  619.         Reg5 bool check_after = (offset <= max_pos_offset);
  620.         Reg6 bool check_before = (offset <= max_neg_offset);
  621.  
  622.         if (check_after && patch_match(first_guess, offset, fuzz)) {
  623. #ifdef DEBUGGING
  624.             if (debug & 1)
  625.                 say3("Offset changing from %ld to %ld\n", last_offset, offset);
  626. #endif
  627.             last_offset = offset;
  628.             return first_guess+offset;
  629.         }
  630.         else if (check_before && patch_match(first_guess, -offset, fuzz)) {
  631. #ifdef DEBUGGING
  632.             if (debug & 1)
  633.                 say3("Offset changing from %ld to %ld\n", last_offset, -offset);
  634. #endif
  635.             last_offset = -offset;
  636.             return first_guess-offset;
  637.         }
  638.         else if (!check_before && !check_after)
  639.             return Nulline;
  640.     }
  641. }
  642.  
  643. /* We did not find the pattern, dump out the hunk so they can handle it. */
  644.  
  645. void
  646. abort_hunk()
  647. {
  648.     Reg1 LINENUM i;
  649.     Reg2 LINENUM pat_end = pch_end();
  650.     /* add in last_offset to guess the same as the previous successful hunk */
  651.     LINENUM oldfirst = pch_first() + last_offset;
  652.     LINENUM newfirst = pch_newfirst() + last_offset;
  653.     LINENUM oldlast = oldfirst + pch_ptrn_lines() - 1;
  654.     LINENUM newlast = newfirst + pch_repl_lines() - 1;
  655.     char *stars = (diff_type >= NEW_CONTEXT_DIFF ? " ****" : "");
  656.     char *minuses = (diff_type >= NEW_CONTEXT_DIFF ? " ----" : " -----");
  657.  
  658.     fprintf(rejfp, "***************\n");
  659.     for (i=0; i<=pat_end; i++) {
  660.         switch (pch_char(i)) {
  661.         case '*':
  662.             if (oldlast < oldfirst)
  663.                 fprintf(rejfp, "*** 0%s\n", stars);
  664.             else if (oldlast == oldfirst)
  665.                 fprintf(rejfp, "*** %ld%s\n", oldfirst, stars);
  666.             else
  667.                 fprintf(rejfp, "*** %ld,%ld%s\n", oldfirst, oldlast, stars);
  668.             break;
  669.         case '=':
  670.             if (newlast < newfirst)
  671.                 fprintf(rejfp, "--- 0%s\n", minuses);
  672.             else if (newlast == newfirst)
  673.                 fprintf(rejfp, "--- %ld%s\n", newfirst, minuses);
  674.             else
  675.                 fprintf(rejfp, "--- %ld,%ld%s\n", newfirst, newlast, minuses);
  676.             break;
  677.         case '\n':
  678.             fprintf(rejfp, "%s", pfetch(i));
  679.             break;
  680.         case ' ': case '-': case '+': case '!':
  681.             fprintf(rejfp, "%c %s", pch_char(i), pfetch(i));
  682.             break;
  683.         default:
  684.             fatal1("fatal internal error in abort_hunk\n");
  685.         }
  686.     }
  687. }
  688.  
  689. /* We found where to apply it (we hope), so do it. */
  690.  
  691. void
  692. apply_hunk(where)
  693. LINENUM where;
  694. {
  695.     Reg1 LINENUM old = 1;
  696.     Reg2 LINENUM lastline = pch_ptrn_lines();
  697.     Reg3 LINENUM new = lastline+1;
  698. #define OUTSIDE 0
  699. #define IN_IFNDEF 1
  700. #define IN_IFDEF 2
  701. #define IN_ELSE 3
  702.     Reg4 int def_state = OUTSIDE;
  703.     Reg5 bool R_do_defines = do_defines;
  704.     Reg6 LINENUM pat_end = pch_end();
  705.  
  706.     where--;
  707.     while (pch_char(new) == '=' || pch_char(new) == '\n')
  708.         new++;
  709.  
  710.     while (old <= lastline) {
  711.         if (pch_char(old) == '-') {
  712.             copy_till(where + old - 1);
  713.             if (R_do_defines) {
  714.                 if (def_state == OUTSIDE) {
  715.                     fputs(not_defined, ofp);
  716.                     def_state = IN_IFNDEF;
  717.                 }
  718.                 else if (def_state == IN_IFDEF) {
  719.                     fputs(else_defined, ofp);
  720.                     def_state = IN_ELSE;
  721.                 }
  722.                 fputs(pfetch(old), ofp);
  723.             }
  724.             last_frozen_line++;
  725.             old++;
  726.         }
  727.         else if (new > pat_end) {
  728.             break;
  729.         }
  730.         else if (pch_char(new) == '+') {
  731.             copy_till(where + old - 1);
  732.             if (R_do_defines) {
  733.                 if (def_state == IN_IFNDEF) {
  734.                     fputs(else_defined, ofp);
  735.                     def_state = IN_ELSE;
  736.                 }
  737.                 else if (def_state == OUTSIDE) {
  738.                     fputs(if_defined, ofp);
  739.                     def_state = IN_IFDEF;
  740.                 }
  741.             }
  742.             fputs(pfetch(new), ofp);
  743.             new++;
  744.         }
  745.         else if (pch_char(new) != pch_char(old)) {
  746.             say3("Out-of-sync patch, lines %ld,%ld--mangled text or line numbers, maybe?\n",
  747.                 pch_hunk_beg() + old,
  748.                 pch_hunk_beg() + new);
  749. #ifdef DEBUGGING
  750.             say3("oldchar = '%c', newchar = '%c'\n",
  751.                 pch_char(old), pch_char(new));
  752. #endif
  753.             my_exit(1);
  754.         }
  755.         else if (pch_char(new) == '!') {
  756.             copy_till(where + old - 1);
  757.             if (R_do_defines) {
  758.                fputs(not_defined, ofp);
  759.                def_state = IN_IFNDEF;
  760.             }
  761.             while (pch_char(old) == '!') {
  762.                 if (R_do_defines) {
  763.                     fputs(pfetch(old), ofp);
  764.                 }
  765.                 last_frozen_line++;
  766.                 old++;
  767.             }
  768.             if (R_do_defines) {
  769.                 fputs(else_defined, ofp);
  770.                 def_state = IN_ELSE;
  771.             }
  772.             while (pch_char(new) == '!') {
  773.                 fputs(pfetch(new), ofp);
  774.                 new++;
  775.             }
  776.         }
  777.         else {
  778.             assert(pch_char(new) == ' ');
  779.             old++;
  780.             new++;
  781.             if (R_do_defines && def_state != OUTSIDE) {
  782.                 fputs(end_defined, ofp);
  783.                 def_state = OUTSIDE;
  784.             }
  785.         }
  786.     }
  787.     if (new <= pat_end && pch_char(new) == '+') {
  788.         copy_till(where + old - 1);
  789.         if (R_do_defines) {
  790.             if (def_state == OUTSIDE) {
  791.                 fputs(if_defined, ofp);
  792.                 def_state = IN_IFDEF;
  793.             }
  794.             else if (def_state == IN_IFNDEF) {
  795.                 fputs(else_defined, ofp);
  796.                 def_state = IN_ELSE;
  797.             }
  798.         }
  799.         while (new <= pat_end && pch_char(new) == '+') {
  800.             fputs(pfetch(new), ofp);
  801.             new++;
  802.         }
  803.     }
  804.     if (R_do_defines && def_state != OUTSIDE) {
  805.         fputs(end_defined, ofp);
  806.     }
  807. }
  808.  
  809. /* Open the new file. */
  810.  
  811. void
  812. init_output(name)
  813. char *name;
  814. {
  815.     ofp = fopen(name, "w");
  816.     if (ofp == Nullfp)
  817.         pfatal2("can't create %s", name);
  818. }
  819.  
  820. /* Open a file to put hunks we can't locate. */
  821.  
  822. void
  823. init_reject(name)
  824. char *name;
  825. {
  826.     rejfp = fopen(name, "w");
  827.     if (rejfp == Nullfp)
  828.         pfatal2("can't create %s", name);
  829. }
  830.  
  831. /* Copy input file to output, up to wherever hunk is to be applied. */
  832.  
  833. void
  834. copy_till(lastline)
  835. Reg1 LINENUM lastline;
  836. {
  837.     Reg2 LINENUM R_last_frozen_line = last_frozen_line;
  838.  
  839.     if (R_last_frozen_line > lastline)
  840.         fatal1("misordered hunks! output would be garbled\n");
  841.     while (R_last_frozen_line < lastline) {
  842.         dump_line(++R_last_frozen_line);
  843.     }
  844.     last_frozen_line = R_last_frozen_line;
  845. }
  846.  
  847. /* Finish copying the input file to the output file. */
  848.  
  849. void
  850. spew_output()
  851. {
  852. #ifdef DEBUGGING
  853.     if (debug & 256)
  854.         say3("il=%ld lfl=%ld\n",input_lines,last_frozen_line);
  855. #endif
  856.     if (input_lines)
  857.         copy_till(input_lines);         /* dump remainder of file */
  858.     Fclose(ofp);
  859.     ofp = Nullfp;
  860. }
  861.  
  862. /* Copy one line from input to output. */
  863.  
  864. void
  865. dump_line(line)
  866. LINENUM line;
  867. {
  868.     Reg1 char *s;
  869.     Reg2 char R_newline = '\n';
  870.  
  871.     /* Note: string is not null terminated. */
  872.     for (s=ifetch(line, 0); putc(*s, ofp) != R_newline; s++) ;
  873. }
  874.  
  875. /* Does the patch pattern match at line base+offset? */
  876.  
  877. bool
  878. patch_match(base, offset, fuzz)
  879. LINENUM base;
  880. LINENUM offset;
  881. LINENUM fuzz;
  882. {
  883.     Reg1 LINENUM pline = 1 + fuzz;
  884.     Reg2 LINENUM iline;
  885.     Reg3 LINENUM pat_lines = pch_ptrn_lines() - fuzz;
  886.  
  887.     for (iline=base+offset+fuzz; pline <= pat_lines; pline++,iline++) {
  888.         if (canonicalize) {
  889.             if (!similar(ifetch(iline, (offset >= 0)),
  890.                          pfetch(pline),
  891.                          pch_line_len(pline) ))
  892.                 return FALSE;
  893.         }
  894.         else if (strnNE(ifetch(iline, (offset >= 0)),
  895.                    pfetch(pline),
  896.                    pch_line_len(pline) ))
  897.             return FALSE;
  898.     }
  899.     return TRUE;
  900. }
  901.  
  902. /* Do two lines match with canonicalized white space? */
  903.  
  904. bool
  905. similar(a,b,len)
  906. Reg1 char *a;
  907. Reg2 char *b;
  908. Reg3 int len;
  909. {
  910.     while (len) {
  911.         if (isspace(*b)) {              /* whitespace (or \n) to match? */
  912.             if (!isspace(*a))           /* no corresponding whitespace? */
  913.                 return FALSE;
  914.             while (len && isspace(*b) && *b != '\n')
  915.                 b++,len--;              /* skip pattern whitespace */
  916.             while (isspace(*a) && *a != '\n')
  917.                 a++;                    /* skip target whitespace */
  918.             if (*a == '\n' || *b == '\n')
  919.                 return (*a == *b);      /* should end in sync */
  920.         }
  921.         else if (*a++ != *b++)          /* match non-whitespace chars */
  922.             return FALSE;
  923.         else
  924.             len--;                      /* probably not necessary */
  925.     }
  926.     return TRUE;                        /* actually, this is not reached */
  927.                                         /* since there is always a \n */
  928. }
  929.  
  930. /* Exit with cleanup. */
  931.  
  932. void
  933. my_exit(status)
  934. int status;
  935. {
  936.     Unlink(TMPINNAME);
  937.     if (!toutkeep) {
  938.         Unlink(TMPOUTNAME);
  939.     }
  940.     if (!trejkeep) {
  941.         Unlink(TMPREJNAME);
  942.     }
  943.     Unlink(TMPPATNAME);
  944.     exit(status);
  945. }
  946.